package org.wannatrak.android.activity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.*;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import org.json.JSONArray;
import org.json.JSONObject;
import org.wannatrak.android.ApplicationContext;
import org.wannatrak.android.R;
import org.wannatrak.android.exceptions.HttpException;
import org.wannatrak.android.helper.DialogHelper;
import org.wannatrak.android.helper.UIHelper;
import org.wannatrak.android.intf.DialogAction;
import org.wannatrak.android.intf.ItemClickAction;
import org.wannatrak.android.maps.PointsOverlay;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Maksim Tulupov maxtulupov@gmail.com
 * @Date: $Date: 2011-06-28 11:16:36 +0000 (Tue, 28 Jun 2011) $
 * @Time: 13:38
 * @Version: $Revision: 23 $
 * @Id: $Id: DeleteTrackActivity.java 23 2011-06-28 11:16:36Z maxtulupov@gmail.com $
 */
public class DeleteTrackActivity extends AbstractContextMenuActivity {

    private Map<String, String> tracks = new HashMap<String, String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.delete_track);
        init();
    }

    private void init() {
        initListView();
    }

    private void initListView() {
        final Dialog dialog = DialogHelper.createProgressDialog(DeleteTrackActivity.this);
        final CustomHandler handler = new CustomHandler();
        dialog.show();
        Runnable r = new Runnable() {
            public void run() {
                Looper.prepare();
                try {
                    ListAdapter adapter = loadTracks();
                    if (adapter != null) {
                        Message message = handler.obtainMessage(1234, adapter);
                        handler.sendMessage(message);
                    }
                } catch (Exception e) {
                    handler.sendMessage(handler.obtainMessage(-1234, e.getMessage()));
                } finally {
                    dialog.dismiss();
                }
            }
        };
        new Thread(r).start();

        ListView listView = (ListView) findViewById(android.R.id.list);
        listView.setEmptyView(findViewById(R.id.emptyView));

        UIHelper.setActionToView((AdapterView) findViewById(android.R.id.list), new ItemClickAction() {
            public boolean onItemSelect(AdapterView parent, View view, int position, long id) {
                TextView tw = (TextView) view.findViewById(android.R.id.text1);
                String trackName = tw.getText().toString();
                String message = getResources().getString(R.string.con_delete_track, trackName);
                Dialog alertDialog = UIHelper.createAlertDialog(DeleteTrackActivity.this, message, -1, false,
                        new DialogAction[]{new OkAction(trackName), new CancelAction()});
                alertDialog.show();
                return true;
            }

            public void onNothingSelected(AdapterView parent) {
            }
        }, UIHelper.ON_CLICK);
    }

    private ArrayAdapter loadTracks() throws Exception {
        JSONArray array = ApplicationContext.getWannatrakService().loadTracks();
        String currentTrack = ApplicationContext.getSettingService().loadSetting("currentTrack");
        String[] arr = new String[array.length()];
        int counter = 0;
        for (int i = 0; i < array.length(); i++) {
            String name = ((JSONObject) array.get(i)).getString("name");
            if (name != null && name.equals(currentTrack)) {
                String[] arr2 = new String[arr.length - 1];
                System.arraycopy(arr, 0, arr2, 0, arr2.length);
                arr = arr2;
                continue;
            }
            String id = ((JSONObject) array.get(i)).getString("id");
            arr[counter++] = name;
            tracks.put(name, id);
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.dropdown_item, arr);
        adapter.setDropDownViewResource(R.layout.dropdown_item);
        return adapter;
    }

    /**
     * creates new adapter without value equals name
     * @param name
     * @return
     */
    private ArrayAdapter createNewAdapter(String name) {
        String[] arr = new String[tracks.size() - 1];
        int i = 0;
        for (String str : tracks.keySet()) {
            if (!str.equals(name)) {
                arr[i++] = str;
            }
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.dropdown_item, arr);
        adapter.setDropDownViewResource(R.layout.dropdown_item);
        return adapter;
    }

    private class CustomHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what >= 0) {
                ListView listView = (ListView) findViewById(android.R.id.list);
                listView.setAdapter((ListAdapter) msg.obj);
            } else {
                UIHelper.createAlertDialog(DeleteTrackActivity.this, (String) msg.obj, -1, true, (DialogAction[]) null).show();
            }
        }
    }

    private class OkAction implements DialogAction {

        private String name;

        private OkAction(String name) {
            this.name = name;
        }

        public void actionPerformed(DialogInterface di, int code) {
            try {
                ApplicationContext.getWannatrakService().deleteTrack(tracks.get(name));
                ApplicationContext.getTrackHistoryService().deleteFromHistory(name);
                ((ListView) findViewById(android.R.id.list)).setAdapter(createNewAdapter(name));
                tracks.remove(name);
            } catch (HttpException e) {
                UIHelper.createAlertDialog(DeleteTrackActivity.this, e.getMessage(), -1, true, (DialogAction[]) null).show();
            } finally {
                di.dismiss();
            }
        }

        public int getNameCode() {
            return R.string.ok;
        }
    }

    private class CancelAction implements DialogAction {
        public void actionPerformed(DialogInterface di, int code) {
            di.dismiss();
        }

        public int getNameCode() {
            return R.string.cancel;
        }
    }
}
